package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.RCompanyRole;
import com.emily.test.model.TCompany;
import com.emily.test.model.TRole;
import com.emily.test.service.RCompanyRoleService;
import com.emily.test.service.RedisService;
import com.emily.test.service.RoleService;
import com.emily.test.service.TCompanyService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.HeaderUtil;
import com.emily.test.vo.CompanyVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公司与角色关系表维护接口
 * @author  田庆新
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "RCompanyRoleController")
@Api(value = "RCompanyRoleControllerApi", description = "公司与角色对应关系管理接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class RCompanyRoleController {

    private Logger logger = LoggerFactory.getLogger(RCompanyRoleController.class);

    @Autowired
    private RCompanyRoleService rCompanyRoleService;

    @Autowired
    private TCompanyService tCompanyService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private RedisService redisService;

    @ApiOperation(value = "根据公司id获取角色信息列表", notes = "")
    @PostMapping(value = "selectRoleByCid")
    public ResponseResult selectRoleByCid(HttpServletRequest request, HttpServletResponse response) {
        try {
            int id = HeaderUtil.getCompanyId(request,redisService);
            List<TRole> roleList = new ArrayList<>();
            List<RCompanyRole> list = rCompanyRoleService.selectRoleIdListByCompanyId(id);
            for(RCompanyRole rCompanyRole:list){
                TRole tRole = roleService.selectRoleById(rCompanyRole.getRoleId());
                roleList.add(tRole);
            }
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, roleList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询角色信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }
    @ApiOperation(value="根据公司ID获取所对应的岗位信息列表", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true)
    })
    @PostMapping(value = "selectRoleIdListByCompanyId")
    public ResponseResult selectRoleIdListByCompanyId(@RequestBody JSONObject jsonObject){
        int companyId = jsonObject.getInteger("companyId");
        try {
            List<RCompanyRole> rCompanyRoleList = rCompanyRoleService.selectRoleIdListByCompanyId(companyId);
            logger.info("根据公司ID获取所对应的岗位信息列表成功,列表信息为：{}",rCompanyRoleList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,rCompanyRoleList);
        } catch (Exception e) {
            logger.error("根据ID查询公司具体信息异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 插入公司与角色关联表信息
     * @param jsonObject 包含公司ID（companyId）与角色（roleIds）关联表集合 ，其中companyId格式为Integer，roleIds格式为List集合
     * @return
     */
    @ApiOperation(value="插入公司与角色关联表信息", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true),
            @ApiImplicitParam(name = "roleIds", value = "角色ID", required = true)
    })
    @PostMapping(value = "insertRCompanyRoleInfo")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult insertTRoleResourceInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
        try {
            int num=rCompanyRoleService.insertTRoleResourceInfo(map);
            if(num==0){
                logger.error("未插入任何公司与角色关联表的数据,插入数据条数:{}",num);
                return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
            }
            logger.info("公司与角色关联表信息"+ReturnValueConstants.ADD_SUCCESS+"增加条数：{}",num);
            return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,num);
        } catch (Exception e) {
            logger.error("插入公司与角色关联表的数据异常{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     *根据公司ID删除对应的角色ID
     * @param jsonObject 其中必须含有companyId
     * @return
     */
    @ApiOperation(value="根据公司ID删除对应的角色ID", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true)
    })
    @PostMapping(value = "deleteRCompanyRoleByCompanyId")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult deleteRCompanyRoleByCompanyId(@RequestBody JSONObject jsonObject){
        Integer companyId=jsonObject.getInteger("companyId");
        if(ConstentUtil.isEmpty(companyId)){
            logger.error("公司ID为空,公司ID={}",companyId);
            return ResponseResult.fail("公司"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            int num= rCompanyRoleService.deleteRCompanyRoleByCompanyId(companyId);
            logger.info("根据公司ID删除相应的角色ID成功，删除的条数={}",num);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS,num);
        } catch (Exception e) {
            logger.error("根据公司ID删除相应的角色ID失败,异常为:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }

    /**
     * 根据公司ID更新公司与角色关系信息表
     * @param jsonObject 包含公司（companyId）与角色（roleIds）关联表集合 ，其中companyId格式为Integer，roleIds格式为List集合
     * @return
     */
    @ApiOperation(value="修改公司ID对应角色ID信息", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true),
            @ApiImplicitParam(name = "roleIds", value = "角色ID")
    })
    @PostMapping(value = "updateRCompanyRoleInfo")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult updateRCompanyRoleInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
//        String companyId=map.get("companyId") == null ? null : (String)map.get("companyId");
//        if(ConstentUtil.isEmpty(companyId)){
//            return ResponseResult.fail("更新失败，公司信息为空，请检查");
//        }
        Integer companyId=Integer.parseInt(map.get("companyId").toString());
        if(ConstentUtil.isEmpty(companyId)){
            logger.error("公司ID不允许为空,companyId={}",companyId);
            return ResponseResult.fail("公司"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            //删除原有公司与角色的对应关系
            int delNum=rCompanyRoleService.deleteRCompanyRoleByCompanyId(companyId);
            logger.info("删除原有公司与角色的绑定关系成功，删除条数={}",delNum);

            //增加新的公司与角色的绑定关系，如果角色信息集合为空，则不需插入
            if(ConstentUtil.isEmpty((List<Integer>)map.get("roleIds"))){
                logger.info("角色信息集合为空，插入的公司与角色信息集合={}",map);
                return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,0);
            }
            int addNum=rCompanyRoleService.insertTRoleResourceInfo(map);

            logger.info("修改公司与角色的绑定关系成功，新增条数={}",addNum);
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS,addNum);
        } catch (Exception e) {
            logger.error("更新r_company_role表失败,异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 根据公司ID获取公司信息以及所有的角色信息集合，其中公司已经有的角色信息添加selected=1属性，没有的则为selected=0.
     * @param jsonObject 包含公司（companyId）与角色（roleIds）关联表集合 ，其中companyId格式为Integer，roleIds格式为List集合
     * @return
     */
    @ApiOperation(value="根据公司ID获取公司信息以及所有的角色信息集合，其中公司已经有的角色信息添加selected=1" +
            "属性，没有的则为selected=0", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID", required = true)
    })
    @PostMapping(value = "getCompanyAndAllRoleInfoByCompanyId")
    public ResponseResult getCompanyAndAllRoleInfoByCompanyId(@RequestBody JSONObject jsonObject){
        try {
            //公司ID
            Integer companyId=jsonObject.getInteger("id");

            //根据公司ID获取公司信息
             CompanyVO vo= tCompanyService.selectCompanyInfoById(companyId);

            //获取公司已经存在的角色信息列表
            List list=new ArrayList();
            list.add(companyId);
            List<Map<String,Object>> tRoleLists= roleService.selectTRoleInfoListByCompanyId(list);

            //获取所有启用的角色信息
            TRole tRole=new TRole();
            tRole.setState(1);
            List<TRole> tRoleList=roleService.selectRoleByCondition(tRole);

            Map<String,Object> returnMapList=new HashMap<String,Object>();
            //将公司信息放入map
            returnMapList.put("id",vo.getId());
            returnMapList.put("cName",vo.getCName());
           // returnMapList.put("loginName",tCompany.getLoginName());
          //  returnMapList.put("password",tCompany.getPassword());
         //   returnMapList.put("cCorporate",tCompany.getcCorporate());
            returnMapList.put("companyState",vo.getState());
            returnMapList.put("companyUpdateTime",vo.getUpdateTime());

            //将角色信息放入集合
            List<Map<String,Object>> inputList=new ArrayList<Map<String,Object>>();
            if(!ConstentUtil.isEmpty(tRoleList)){
                for(TRole tRoles : tRoleList){

                    int allRoleId=tRoles.getId();

                    Map<String,Object> roleMap=new HashMap<>();
                    roleMap.put("roleId",tRoles.getId());
                    roleMap.put("rName",tRoles.getrName());
                    roleMap.put("rCode",tRoles.getrCode());
                    roleMap.put("roleState",tRoles.getState());
                    roleMap.put("roleSerial",tRoles.getSerial());
                    roleMap.put("RoleDescription",tRoles.getDescription());
                    roleMap.put("roleUpdateTime",tRoles.getUpdateTime());

                    if(!ConstentUtil.isEmpty(tRoleLists)){
                        for(Map<String,Object> rMap : tRoleLists){
                            int partRoleId=(int) rMap.get("roleId");
                            //添加公司含有的角色信息到map，并且为其添加属性selected ： true
                            if(allRoleId==partRoleId){
                                roleMap.put("selected","1");
                                break;
                            }else{
                                roleMap.put("selected","0");
                            }
                        }
                    }else{
                        roleMap.put("selected","0");
                    }
                    inputList.add(roleMap);
                }
            }
            returnMapList.put("roleList",inputList);
            logger.info("查询公司角色信息成功:{}",returnMapList);
            return ResponseResult.success(returnMapList);
             } catch (Exception e) {
                logger.error("查询公司角色信息异常",e);
                 e.printStackTrace();
                 return ResponseResult.fail("查询失败");
             }

    }
    /**
     * 根据公司信息查询公司与角色的关联信息
     * @param jsonObject 包含公司信息
     * @return  符合查询条件公司与角色的相关信息列表
     */
    @ApiOperation(value="根据公司信息查询公司与角色的关联信息列表", notes="RCompanyRole")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID"),
            @ApiImplicitParam(name = "cName", value = "公司名称"),
            @ApiImplicitParam(name = "loginName", value = "公司登录名"),
            @ApiImplicitParam(name = "password", value = "登录密码"),
            @ApiImplicitParam(name = "cCorporate", value = "公司法人"),
            @ApiImplicitParam(name = "state", value = "启用状态"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间")
    })
    @PostMapping("getCompanyRoleInfoListByComCondition")
    public ResponseResult getCompanyRoleInfoListByComCondition(@RequestBody JSONObject jsonObject){

        List<Map<String,Object>> all_list = new ArrayList<Map<String,Object>>();
        Integer id=jsonObject.getInteger("id");
        String cName=jsonObject.getString("cName");
        String loginName=jsonObject.getString("loginName");
        String password=jsonObject.getString("password");
        String cCorporate=jsonObject.getString("cCorporate");
        String updateTime=jsonObject.getString("updateTime");
        TCompany tCompany=new TCompany();
//        tCompany.setId(id);
//        tCompany.setLoginName(loginName);
//        tCompany.setcName(cName);
//        tCompany.setPassword(password);
//        tCompany.setcCorporate(cCorporate);
//        tCompany.setUpdateTime(updateTime);
        try {
            //根据条件查询公司信息列表
            List<TCompany> resourceList=tCompanyService.getCompanyList(tCompany);
            if(!ConstentUtil.isEmpty(resourceList)){
                String stringBuffer="";
                for(TCompany tCompany1 : resourceList){
                    stringBuffer +=tCompany1.getId()+",";
                }
                stringBuffer= stringBuffer.substring(0,stringBuffer.length()-1).trim();
                List li=ConstentUtil.strToList(stringBuffer);

                List<Map<String,Object>> tRoleList= roleService.selectTRoleInfoListByCompanyId(li);
                if(!ConstentUtil.isEmpty(tRoleList)){

                    String[] strs = stringBuffer.split(",");
                    for (int j = 0; j < strs.length; j++) {
                        HashMap<String, Object> hm = new HashMap<>();
                        List list1 = new ArrayList();
                        for (int i = 0; i < tRoleList.size(); i++) {
                            if(strs[j].equals(tRoleList.get(i).get("companyId").toString())) {
                                hm.put("companyId", strs[j]);
                                hm.put("cName", tRoleList.get(i).get("cName").toString());
                                list1.add(tRoleList.get(i));
                                hm.put("data",list1);
                            }
                        }
                        if(hm.size()!=0){
                            all_list.add(hm);
                        }
                    }
                }
            }
            logger.info("查询公司与角色信息成功:{}",all_list);
            return ResponseResult.success(all_list);
        } catch (Exception e) {
            logger.error("查询公司与角色信息异常:",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }
}
